#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
#include "Consumer.h"
#include "ProducerConsumerUtilities.h"
void getProduct(ProducerConsumerManager_t *producerConsumerMgr, int threadIdx){
	sem_t *mutex = &(producerConsumerMgr->mutex);
	sem_t *full = &(producerConsumerMgr->full);
	sem_t *empty = &(producerConsumerMgr->empty);
	int productGetted;
	
	//等待有产品可消费，若缓冲区为空则线程进入阻塞，若成功则full信号量减1
	semWait(full);//before accessing buffer
	//请求独占访问缓冲区的权限
	semWait(mutex);
	
	//临界区开始，取出产品并更新数据
	productGetted = producerConsumerMgr->buffer[producerConsumerMgr->consumerOffset];
	producerConsumerMgr->consumerOffset = (producerConsumerMgr->consumerOffset + 1) % producerConsumerMgr->bufferSize;
	--producerConsumerMgr->remainProducts;
	//打印消费信息
	printf("Consumer:%d, get product:%d\n",threadIdx, productGetted);
	
	//释放互斥锁，并通知生产者缓冲区新增了一个空位，empty信号量加1
	semSignal(mutex);//after accessing buffer
	semSignal(empty);
}

//线程入口函数
void *consumerThread(void *arg){
	//获得共享管理器和线程
	ThreadStruct_t *curThreadStruct = (ThreadStruct_t *)arg;ProducerConsumerManager_t *producerConsumerMgr = 
	curThreadStruct->producerConsumerMgr;
	while(curThreadStruct->producerConsumerMgr->exit_flag == 0){
		//消费一个产品
		getProduct(producerConsumerMgr, curThreadStruct->threadIdx);
		//暂停一段时间，模拟消费耗时
		sleep(WAIT_TIME_IN_SECOND);// wait WAIT_TIME_IN_SECOND seconds
	}
	 
	return arg;
}
